import { FC, useEffect, useRef, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import pic from '../../resource/pic.png'
import arrow from '../../resource/arrow.png'
import style from './style.less'
import { Button, ScrollView } from '@tarojs/components'

const Index: FC = () => {
  const [check, setCheck] = useState(0)
  const [token, setToken] = useState(() => Taro.getStorageSync('token'))
  const [auth, setAuth] = useState(() => Taro.getStorageSync('auth'))
  const [vip, setVip] = useState(() => Taro.getStorageSync('vip'))
  const [refreshing, setRefreshing] = useState(false)

  const pageNum = useRef(1)
  const pageSize = useRef(10)

  const pageNum2 = useRef(1)
  const pageSize2 = useRef(10)

  const [list, setList] = useState<any[]>([])
  const [history, setHistory] = useState<any[]>([])

  useEffect(() => {
    if (auth) {
      getListReq(1, 10)
      getHistoryReq(1, 10)
    }
  }, [])

  useDidShow(() => {
    setToken(() => Taro.getStorageSync('token'))
    setAuth(() => Taro.getStorageSync('auth'))
    setVip(() => Taro.getStorageSync('vip'))

    if (Taro.getStorageSync('refresh')) {
      console.log('我要刷新');
      pageNum.current = 1
      getListReq(pageNum.current, pageSize.current)
      Taro.removeStorageSync('refresh')
    }
  })

  const getListReq = (pageNum, pageSize) => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-cargo/blackboard/cargoBlackboard',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token'),
        pageNum,
        pageSize
      }),
      success: (data) => {
        if (list.length === data.data.data.list.length && pageNum !== 1) {
          Taro.showToast({
            title: '已经到底了',
            icon: 'none',
            duration: 1500
          })
          return
        }
        console.log('获得发货中', data);
        setList(data.data.data.list)
        Taro.hideLoading()
        setRefreshing(false)
      },
      fail: () => {
        Taro.hideLoading()
        console.log('查询发货列表失败');
        setRefreshing(false)
      }
    })
  }

  const getHistoryReq = (pageNum2, pageSize2) => {
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-cargo/blackboard/cargoBlackboardHistory',
      method: 'POST',
      data: JSON.stringify({
        openId: token,
        pageNum: pageNum2,
        pageSize: pageSize2
      }),
      success: (data) => {
        if (history.length === data.data.data.list.length && pageNum2 !== 1) {
          Taro.showToast({
            title: '已经到底了',
            icon: 'none',
            duration: 1500
          })
          return
        }
        console.log('获得发货历史', data);
        setHistory(data.data.data.list)
        setRefreshing(false)
        Taro.hideLoading()
      },
      fail: () => {
        console.log('查询发货历史失败');
        setRefreshing(false)
        Taro.hideLoading()
      }
    })
  }

  const bindScrollToRefresh = () => {
    setRefreshing(true)
    pageNum.current = 1
    getListReq(pageNum.current, pageSize.current)
  }

  const bindScrollToLower = () => {
    pageNum.current += 1
    getListReq(pageNum.current, pageSize.current)
  }

  const bindScrollToRefresh2 = () => {
    setRefreshing(true)
    pageNum2.current = 1
    Taro.showLoading({ title: '刷新中' })
    getHistoryReq(pageNum2.current, pageSize2.current)
  }

  const bindScrollToLower2 = () => {
    pageNum2.current += 1
    Taro.showLoading({ title: '加载中' })
    getHistoryReq(pageNum2.current, pageSize2.current)
  }

  const deleteItem = (id) => {
    Taro.showModal({
      content: '您确定要删除该运单吗？',
      success: function (res) {
        if (res.confirm) {
          Taro.request({
            url: 'http://10.190.84.29:9527/fta-cargo/blackboard/deleteCargo',
            method: 'POST',
            data: JSON.stringify({
              cargoId: id
            }),
            success: (data) => {
              if (data.data.data.result) {
                pageNum.current = 1
                pageNum2.current = 1
                getListReq(pageNum.current, pageSize.current)
                getHistoryReq(pageNum2.current, pageSize.current)
              } else {
                Taro.showToast({
                  title: '删除失败',
                  icon: 'none',
                  duration: 1500
                })
              }
            },
            fail: () => {
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

  const getGoodsList = () => {
    if (!list.length) {
      return <img src={pic} alt="" className="bgi" />
    }
    // 请求发货中状态的列表
    return (
      <ScrollView
        className="goodsList"
        scrollY
        lowerThreshold={5}
        refresherEnabled
        refresherBackground='#f5f5f5'
        refresherTriggered={refreshing}
        onRefresherRefresh={bindScrollToRefresh}
        onScrollToLower={bindScrollToLower}
      >
        {list?.map(item => {
          return (
            <div className="deliver" key={item.id}>
              <div className="container">
                <div className="area">
                  {item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}
                </div>
                <img src={arrow} alt="" className="arrow" />
                <div className="area">
                  {item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}
                </div>
              </div>
              <div className="amount">¥{item.cargoFee}/趟</div>
              <div className="money">订金{item.deposit}</div>
              <div className="info">{item.cargoName} | {item.truckLength}米 {item.truckType} | {item.truckWeight}吨/{item.cargoCapacipy}方</div>
              <div className="time">{item.loadTime}</div>
              <div className="distance">总里程：{item.mileage}公里</div>
              <div className="btns">
                <Button className="btnItem" onClick={() => { deleteItem(item.cargoId) }}>删除</Button>
                <Button className="btnItem" onClick={() => { Taro.navigateTo({ url: `/packageB/edit/index?param=${JSON.stringify(item)}&orderNumber=0` }) }}>编辑</Button>
              </div>
            </div>
          )
        })}
      </ScrollView>
    )
  }

  const getHistoryList = () => {
    if (!history.length) {
      return <img src={pic} alt="" className="bgi" />
    }
    // 请求发货中状态的列表
    return (
      <ScrollView
        className="goodsList"
        scrollY
        lowerThreshold={5}
        refresherEnabled
        refresherBackground='#f5f5f5'
        refresherTriggered={refreshing}
        onRefresherRefresh={bindScrollToRefresh2}
        onScrollToLower={bindScrollToLower2}
      >
        {history?.map(item => {
          return (
            <div className="deliver" style={{ height: Taro.pxTransform(222) }} key={item.id}>
              <div className="container">
                <div className="area">
                  {item.loadAddress.substring(item.loadAddress.indexOf('-') + 1, item.loadAddress.indexOf(' '))}
                </div>
                <img src={arrow} alt="" className="arrow" />
                <div className="area">
                  {item.unloadingAdress.substring(item.unloadingAdress.indexOf('-') + 1, item.unloadingAdress.indexOf(' '))}
                </div>
              </div>
              <div className="amount" style={{ color: '#000' }}>¥{item.cargoFee}/趟</div>
              <div className="money" style={{ color: '#000' }}>订金{item.deposit}</div>
              <div className="info">{item.cargoName} | {item.truckLength}米 {item.truckType} | {item.truckWeight}吨/{item.cargoCapacipy}方</div>
              <div className="time">{item.loadTime}</div>
              <div className="distance">总里程：{item.mileage}公里</div>
              <div className="status" style={{ color: item.cargoStatus === 20 ? '#FA8624' : item.cargoStatus === 30 ? '#23E915' : '#FA3724' }}>
                {item.cargoStatus === 20 ? '· 运输中' : item.cargoStatus === 30 ? '· 已成交' : '· 已下架'}
              </div>
            </div>
          )
        })}
      </ScrollView>
    )
  }

  const sendCommon = () => {
    // 未认证或未登录
    if (!auth) {
      Taro.showModal({
        title: '提示',
        content: token ? '您还未认证，点击确定去到认证页面' : '您还未登录，点击确定去到登录页面',
        success: function (res) {
          if (res.confirm) {
            ok()
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      })
      return
    }
    // 认证用户
    Taro.navigateTo({ url: '/packageB/deliver/common/index' })
  }

  const ok = () => {
    if (token) {
      Taro.navigateTo({
        url: '/packageA/authentication/index'
      })
    } else {
      Taro.navigateTo({
        url: '/packageA/login/index'
      })
    }
  }

  return (
    <div className={style.root}>
      <div className="main">
        <div className="title">满满运</div>
        <div className="nav">
          <div className={check === 0 ? "nav-item checked" : "nav-item"} onClick={() => { setCheck(0) }}>发货中</div>
          <div className={check === 1 ? "nav-item checked" : "nav-item"} onClick={() => { setCheck(1) }}>发货历史</div>
        </div>
        <div className={check ? "r-line" : "l-line"} />
      </div>
      {Taro.getStorageSync('auth') ? check ? getHistoryList() : getGoodsList() : <img src={pic} alt="" className="bgi" />}
      <div className="goods">
        <div className="goods-common" onClick={sendCommon}>我要发货</div>
      </div>
    </div>
  )
}

export default Index